#    This file is part of OpenPolitik.
#
#    OpenPolitik is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    OpenPolitik is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with OpenPolitik.  If not, see <http://www.gnu.org/licenses/>.
import os
import re
import urllib

import session

from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import op_models
import helpers

class Compose(webapp.RequestHandler):
	def get(self, email):
		email = urllib.unquote(urllib.unquote(email))
		template_values = helpers.get_liu_stuff(self.request.uri)
		liu = template_values["liu"]

		if liu == None:
			self.redirect(template_values["login_url"])
			return

		to = users.User(email)
		game = op_models.Game.get(self.request.get("game"))

		uig = op_models.UserInGame.gql("WHERE user = :1 AND game = :2", to, game).fetch(1)

		page = "compose"
		if game == None or uig == None:
			page = "_404"
		else:
			if game.state != 0:
				template_values["nation"] = uig[0].nation
			template_values["to"] = to
			template_values["game"] = game
		
		self.response.out.write(template.render(helpers.get_path(page), template_values))
	
	def post(self, email):
		email = urllib.unquote(urllib.unquote(email))
		template_values = helpers.get_liu_stuff(self.request.uri)
		liu = template_values["liu"]

		if liu == None:
			self.redirect(template_values["login_url"])
			return

		s = session.Session()

		to = users.User(email)
		game = op_models.Game.get(self.request.get("game"))

		subject = self.request.get("subject")
		if subject == "":
			subject = "( no subject )"

		content = self.request.get("content")

		msg = op_models.Message(to=to, sender=liu, game=game, subject=subject, content=content)
		key = msg.put()

		# send an email
		prefs = op_models.UserOptions.get_prefs(to)
		if prefs.prefs & op_models.UserOptions.SEND_EMAIL_ON_MESSAGE != 0:
			mail.send_mail(sender=liu.email(),
						   to=prefs.email,
						   subject="%s has sent you a message on OpenPolitik." % liu.nickname(),
						   body="""
Hello %s,

%s has sent you a message in OpenPolitik titled "%s".

Click here to see the message: %s
""" % (to.nickname(), liu.nickname(), subject, "http://openpolitik.appspot.com/show_message/" + str(key)))

		s["flash_msg"] = "Your message has been sent."
		self.redirect("/game?game=" + str(game.key()))

class ShowMessage(webapp.RequestHandler):
	def get(self, message):
		message = urllib.unquote(urllib.unquote(message))
		template_values = helpers.get_liu_stuff(self.request.uri)
		liu = template_values["liu"]

		if liu == None:
			self.redirect(template_values["login_url"])
			return

		message = op_models.Message.get(db.Key(message))
		if message == None:
			self.response.out.write(template.render(helpers.get_path("_404"), template_values))
			return

		if message.orig:
			messages = op_models.Message.gql("WHERE orig = :1", message.orig).fetch(100)
			messages.insert(0, message.orig)
			orig = message.orig
		else:
			messages = op_models.Message.gql("WHERE orig = :1", message).fetch(100)
			messages.insert(0, message)
			orig = message
			
		if len(messages) > 10:
			template_values["old_messages"] = messages[0:-10]
			messages = messages[-10:]

		for m in messages:
			m.content = m.content.replace("\n", "<br />")

		template_values["orig"] = orig
		template_values["messages"] = messages
		template_values["message"] = message

		if liu == message.to:
			other = message.sender
		else:
			other = message.to

		uig = op_models.UserInGame.gql("WHERE user = :1 AND game = :2", other, message.game).fetch(1)
		
		template_values["other_nation"] = uig[0].nation
		template_values["other"] = other

		self.response.out.write(template.render(helpers.get_path("show_message"), template_values))

class Reply(webapp.RequestHandler):
	def post(self):
		liu = users.get_current_user()
		
		if not liu:
			return

		to = users.User(self.request.get("to"))
		game = op_models.Game.get(self.request.get("game"))
		orig = op_models.Message.get(self.request.get("orig"))

		subject = self.request.get("subject")
		if subject == "":
			subject = "( no subject )"

		content = self.request.get("content")

		msg = op_models.Message(to=to, sender=liu, game=game, subject=subject, content=content, orig=orig)
		key = msg.put()

		prefs = op_models.UserOptions.get_prefs(to)
		if prefs.prefs & op_models.UserOptions.SEND_EMAIL_ON_MESSAGE != 0:
			mail.send_mail(sender=liu.email(),
						   to=prefs.email,
						   subject="%s has replied to a message on OpenPolitik." % liu.nickname(),
						   body="""
Hello %s,

%s has replied to your message in OpenPolitik titled "%s".

Click here to see the message: %s
""" % (to.nickname(), liu.nickname(), orig.subject, "http://openpolitik.appspot.com/show_message/" + str(key)))

class DeleteMessage(webapp.RequestHandler):
	def post(self):
		# AJAX call
		liu = users.get_current_user()

		if not liu:
			return

		message = op_models.Message.get(self.request.get("message"))

		if not message or liu != message.to:
			return

		message.delete()

		self.response.out.write("")
